package com.kly.pay.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.enums.SubscriptionProcessStatus;
import com.kly.order.db.dao.PSubscriptionLogDao;
import com.kly.order.db.entity.PSubscriptionLogEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 续订失败重试处理
 */
@Component
public class RetrySubscriptionTask {
    private static Log logger = LogFactory.getLog(RetrySubscriptionTask.class);

    @Resource
    PSubscriptionLogDao subscriptionLogDao;
    @NacosValue(value = "${callback.url:http://localhost:9104/api/order/subscriptionOrder/}", autoRefreshed = true)
    private String callbackUrl;


    @Scheduled(fixedDelay = 1000*3600)
    public void execute() {
        logger.info("=============RetrySubscriptionTask.execute Start==================");
        final List<PSubscriptionLogEntity> needProcessRecordList = subscriptionLogDao.listSubscriptFailRecord();
        if (CollectionUtils.isEmpty(needProcessRecordList)) {
            return;
        }
        for (PSubscriptionLogEntity subscription : needProcessRecordList) {
            final String receiveNotifyMsg = subscription.getReceiveNotifyMsg();
            if (StringUtils.isNotEmpty(receiveNotifyMsg)) {
                final JSONObject msgJson = JSONObject.parseObject(receiveNotifyMsg);
                final String result = HttpUtil.getPage(callbackUrl + subscription.getMessageId() + "/" + msgJson.getString("data"));
                logger.info("====记录：{}, 返回：{}", JSONObject.toJSONString(subscription), result);
                if (!"ok".equals(result)) {
                    subscriptionLogDao.updateSubscriptionStatus(subscription.getMessageId(), SubscriptionProcessStatus.PAID_FAILED.getStatus(), "fail: 重试处理失败");
                }
            }
        }

        logger.info("=================RetrySubscriptionTask.execute End==============");
    }

}
